package com.yuhanginfo.modules.sys.service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.service.CrudService;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.GoodsMateriel;
import com.yuhanginfo.modules.sys.entity.StoreGoods;
import com.yuhanginfo.modules.sys.utils.CodeUtil;
import com.yuhanginfo.modules.sys.utils.UserUtils;
import com.yuhanginfo.modules.sys.dao.GoodsDao;
import com.yuhanginfo.modules.sys.dao.GoodsMaterielDao;
import com.yuhanginfo.modules.sys.dao.StoreGoodsDao;

/**
 * 门店商品信息管理Service
 * 
 * @author yinhao
 * @version 2017-09-11
 */
@Service
@Transactional(readOnly = true)
public class GoodsStoreMangerService extends CrudService<GoodsDao, Goods> {
	public static final Logger logger =  LoggerFactory.getLogger(GoodsStoreMangerService.class);
	@Autowired
	GoodsDao goodsDao;
	
	@Autowired
	GoodsMaterielDao goodsMaterielDao;
	
	@Autowired
	StoreGoodsDao storeGoodsDao;
	

	


	

	public List<Goods> findExportList(Goods goods) {
		return goodsDao.findExportList(goods);
	}
	
	public Page<Goods> findPage(Page<Goods> page, Goods goods) {
		goods.setPage(page);
		return page.setList(goodsDao.findListBySysUser(goods));
	}

	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void save(String userId, Goods goods, String image, String detail, String service,String[] imageSelect,String[] detailSelect,String[] serviceSelect){
		
			//存在则假删除
			if(goods.getId() != null && !"".equals(goods.getId())){
				super.delete(goods);
				GoodsMateriel delGoodsMateriel = new GoodsMateriel();
				delGoodsMateriel.setGoodsCode(goods.getCode());
				goodsMaterielDao.delete(delGoodsMateriel);
				StoreGoods delStoreGoods = new StoreGoods();
				delStoreGoods.setIsHistorySell(1);
				delStoreGoods.setStoreCode(goods.getStoreCode());
				delStoreGoods.setGoodsCode(goods.getCode());
				storeGoodsDao.delete(delStoreGoods);
			}
			String goodsCode = CodeUtil.getStoreGoodsCode();
			goods.setImage(this.sortImg(this.formatImg(goods.getDeleteImage(),goods.getImage(),image), imageSelect));
			goods.setDetail(this.sortImg(this.formatImg(goods.getDeleteDetail(),goods.getDetail(),detail),detailSelect));
			goods.setService(this.sortImg(this.formatImg(goods.getDeleteService(),goods.getService(),service),serviceSelect));
			goods.setCode(goodsCode);
			goods.setStatus(0);
			goods.setSource("3");
			goods.setExamineStatus("1");
			goods.setIsNewRecord(true);
			super.save(goods);
			//商品物料关系
			GoodsMateriel goodsMateriel = new GoodsMateriel();
			goodsMateriel.setGoodsCode(goods.getCode());
			goodsMateriel.setMaterielCode(goods.getMaterielCode());
			goodsMateriel.setCreateDate(goods.getCreateDate());
			goodsMateriel.setCreateBy(goods.getCreateBy());
			goodsMateriel.setUpdateDate(goods.getUpdateDate());
			goodsMateriel.setUpdateBy(goods.getUpdateBy());
			goodsMateriel.setIsNewRecord(true);
			goodsMaterielDao.insert(goodsMateriel);
			//商品门店关系
			StoreGoods storeGoods = new StoreGoods();
			storeGoods.setStoreCode(goods.getStoreCode());
			storeGoods.setGoodsCode(goodsCode);
			storeGoods.setStock(1);
			storeGoods.setIsHistorySell(0);
			storeGoods.setIsHisttoryStocks(0);
			storeGoods.setCreateDate(goods.getCreateDate());
			storeGoods.setCreateBy(goods.getCreateBy());
			storeGoods.setUpdateDate(goods.getUpdateDate());
			storeGoods.setUpdateBy(goods.getUpdateBy());
			storeGoodsDao.insert(storeGoods);
		
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void examine(Goods goods) throws Exception {
		try {
			super.save(goods);
		} catch (Exception ex) {
			logger.debug("",ex);
		}
	}

	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void batchExamine(String[] arrayId) throws Exception {
		try {
			for(int i=0;i<arrayId.length;i++){
				Goods queryGoods = new Goods();
				queryGoods.setId(arrayId[i]);
				Goods resultGoods = goodsDao.get(queryGoods);
				if("1".equals(resultGoods.getExamineStatus()) && "3".equals(resultGoods.getSource())){
					queryGoods.setUpdateBy(UserUtils.getUser());
					queryGoods.setUpdateDate(new Date());
					queryGoods.setExamineStatus("2");
					goodsDao.update(queryGoods);
				}
			}
		} catch (Exception ex) {
			logger.debug("",ex);
		}
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Map<String,Object> del(Goods goods) {
			Map<String,Object> resultMap = new HashMap<>();
			if(goods.getStatus() == 1 && "3".equals(goods.getSource())){
				resultMap.put("resultCode", 0);
				resultMap.put("resultMessage", "该商品为上架状态，不可删除！");
				return resultMap;
			}
			super.delete(goods);
			//删除商品门店关系
			StoreGoods storeGoods = new StoreGoods();
			storeGoods.setGoodsCode(goods.getCode());
			storeGoods.setUpdateDate(goods.getUpdateDate());
			storeGoods.setUpdateBy(goods.getUpdateBy());
			storeGoodsDao.delete(storeGoods);
			return resultMap;
	}
	
	@Transactional(readOnly = false,propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void batchDel(String[] arrayId) {
			for(int i=0;i<arrayId.length;i++){
				Goods queryGoods = new Goods();
				queryGoods.setId(arrayId[i]);
				Goods resultGoods = goodsDao.get(queryGoods);
				if(resultGoods.getStatus() != 1 && "3".equals(resultGoods.getSource())){
					super.delete(queryGoods);
					StoreGoods storeGoods = new StoreGoods();
					storeGoods.setGoodsCode(resultGoods.getCode());
					storeGoods.setUpdateDate(new Date());
					storeGoods.setUpdateBy(UserUtils.getUser());
					storeGoodsDao.delete(storeGoods);
				}
			}
	}
	
	//对比文件名，将未删除的文件和新上传的文件组合保留
		private String formatImg(String delImg,String oldImg,String newImg){
			String finalImg = "";
			boolean delFlagFlag = false;
			if( null!=delImg && !"".equals(delImg) && null!=oldImg && !"".equals(oldImg)){
				String[]  delImgArray = delImg.split(";");
				String[]  oldImgArray = oldImg.split(";");
				for(int i=0;i<oldImgArray.length;i++){
					boolean delFlag = true;
					for(int y=0;y<delImgArray.length;y++){
						
						if(oldImgArray[i].substring(oldImgArray[i].lastIndexOf('/')+1, oldImgArray[i].lastIndexOf('.')).equals(delImgArray[y])){
							delFlag = false;
							break;
						}
					}
					if(delFlag){
						if(delFlagFlag){
							finalImg += ";";
						}
						if(!delFlagFlag){
							delFlagFlag = true;
						}
						finalImg += oldImgArray[i];
					}
				}
			}else if( null!=oldImg && !"".equals(oldImg)){
				finalImg += oldImg;
			}
			if( null!=newImg && !"".equals(newImg)){
				if(finalImg != null && !"".equals(finalImg)){
					finalImg += ";";
				}
				finalImg += newImg;
			}
			return finalImg;
		}
		
		private String sortImg(String img,String[] sort){
			if(sort == null){
				return img;
			}
			StringBuilder finalImg = new StringBuilder();
			String[] imgList = img.split(";");
		
			for(int i=0;i<sort.length;i++){
				if(i>0){
					finalImg.append(";");
				}
				finalImg.append(imgList[Integer.valueOf(sort[i])-1]);
			}
			return finalImg.toString();
		}
}